package com.proxy.register;

import com.proxy.annotation.Proxy;
import com.proxy.configure.ProxyScannerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @author Better Feng
 * @date 2021/8/27 11:26
 */
public class AutoProxyScannerRegister implements BeanFactoryAware, ImportBeanDefinitionRegistrar {

    private static final Logger logger = LoggerFactory.getLogger(AutoProxyScannerRegister.class);

    private BeanFactory beanFactory;

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        if (!AutoConfigurationPackages.has(this.beanFactory)) {
            logger.debug("Could not determine auto-configuration package, automatic mapper scanning disabled.");
            return;
        }

        logger.debug("Searching for proxy annotated with @Proxy");

        List<String> basePackages = AutoConfigurationPackages.get(this.beanFactory);
        if (logger.isDebugEnabled()) {
            basePackages.forEach(pkg -> logger.debug("Using auto-configuration base package '{}'", pkg));
        }
        BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(ProxyScannerConfiguration.class);
        builder.addPropertyValue("basePackage", StringUtils.collectionToCommaDelimitedString(basePackages));
        builder.addPropertyValue("annotationClass", Proxy.class);
        registry.registerBeanDefinition(ProxyScannerConfiguration.class.getName(), builder.getBeanDefinition());
    }
}
